<?php
namespace dk\core;
      
class Servicemanager{
    protected $config = array();
    private $instances = array();

    public function __construct($config) {
        $this->config = $config;
    }

    public function setClass($name, $obj){
        $this->config[$name] = $obj;
    }

    /**
     * @param $name
     * @return mixed
     * @throws Exception
     */
    public function get($name){
        if(isset($this->instances[$name])){
            return $this->instances[$name];
        }

        if(!isset($this->config[$name])){
            if(class_exists($name)){
                $instance = new $name();
            }else{
                throw new Exception("Class({$name}) not found");
            }
        }

        $className = $this->config[$name];
        if(is_callable($className)){
            $instance = call_user_func($className);
        }else{
            if(class_exists($className)){
                $instance = new $className();
            }else{
                throw new Exception("Class({$name}) not found");
            }
        }

        $this->instances[$name] = $instance;
        return $instance;
    }
}